import {
  SET_ERR_MSG,
  SET_LOGIN_RESP,
  PUSH_PAGE_STACK,
  POP_PAGE_STACK,
  SET_PAGE_STACK,
  SET_PAGE_TITLE,
  SET_SHOW_HOME_BTN,
  UPDATE_TOKEN,
  CLEAR_ALL,
  SET_SCAN_DATA
} from "./action-types";

const initialState = {
  errMsg: null,
  token: null,
  perms: null,
  displayName: null,
  avatar: null,
  pageStack: [],
  pageTitle: null,
  showHomeBtn: true,
  scandata: null
};

const handleClearAll = (state) => {
  window.sessionStorage.clear();
  return {
    ...state,
    errMsg: null,
    token: null,
    perms: null,
    displayName: null,
    avatar: null,
    pageStack: [],
    pageTitle: null,
    showHomeBtn: true,
  };
};

const handleUpdateToken = (state, payload) => {
  let { token, perms } = payload;
  window.sessionStorage.setItem("perms", JSON.stringify(perms));
  window.sessionStorage.setItem("token", token);
  return { ...state, token, perms };
};

const handleSetLoginResp = (state, payload) => {
  let { token, perms, displayName, avatar } = payload;
  window.sessionStorage.setItem("perms", JSON.stringify(perms));
  window.sessionStorage.setItem("token", token);
  window.sessionStorage.setItem("displayName", displayName);
  window.sessionStorage.setItem("avatar", avatar);
  return { ...state, token, perms, displayName, avatar };
};

const handlePopPageStack = (state, navigate) => {
  let stack = [...state.pageStack];
  stack.pop();
  if (navigate) {
    let url = stack.slice(-1);
    if (url.length > 0) {
      navigate(url[0]);
    }
  }
  return { ...state, pageStack: stack };
};

const data = (state = initialState, action) => {
  switch (action.type) {
    case SET_ERR_MSG:
      return { ...state, errMsg: action.payload };
    case SET_LOGIN_RESP:
      return handleSetLoginResp(state, action.payload);
    case PUSH_PAGE_STACK:
      return { ...state, pageStack: [...state.pageStack, action.payload] };
    case POP_PAGE_STACK:
      return handlePopPageStack(state, action.payload);
    case SET_PAGE_STACK:
      return { ...state, pageStack: action.payload };
    case SET_PAGE_TITLE:
      return { ...state, pageTitle: action.payload };
    case SET_SHOW_HOME_BTN:
      return { ...state, showHomeBtn: action.payload };
    case UPDATE_TOKEN:
      return handleUpdateToken(state, action.payload);
    case CLEAR_ALL:
      return handleClearAll(state);
    case SET_SCAN_DATA:
      return { ...state, scandata: action.payload };
    default:
      return state;
  }
};

export default data;
